package com.uzhie.jt808.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.util.ReferenceCountUtil;
import org.apache.log4j.Logger;

import java.net.SocketAddress;

/**
 * Created by TangFei on 2018/8/28.
 * 发送给服务端的消息
 */
@ChannelHandler.Sharable
public class OutHandler extends ChannelOutboundHandlerAdapter {

    private Logger logger = Logger.getLogger(getClass());

    public OutHandler() {
        super();
    }

    @Override
    public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception {
        super.bind(ctx, localAddress, promise);
        logger.debug("OutHandler bind");
    }

    @Override
    public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception {
        super.connect(ctx, remoteAddress, localAddress, promise);
        logger.debug("OutHandler connect");
    }

    @Override
    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        super.disconnect(ctx, promise);
        logger.debug("OutHandler disconnect");
    }

    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        super.close(ctx, promise);
        logger.debug("OutHandler close");
    }

    @Override
    public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        super.deregister(ctx, promise);
        logger.debug("OutHandler deregister");
    }

    @Override
    public void read(ChannelHandlerContext ctx) throws Exception {
        ctx.read();
        logger.debug("OutHandler read");
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
//        super.write(ctx, msg, promise);
        ctx.write(msg);
        ReferenceCountUtil.release(msg);
        promise.setSuccess();
        logger.debug("OutHandler write");
    }

    @Override
    public void flush(ChannelHandlerContext ctx) throws Exception {
//        super.flush(ctx);
        ctx.flush();
        logger.debug("OutHandler flush");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        logger.debug("OutHandler exceptionCaught", cause);
    }
}
